package com.migu.spms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.RuntimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.migu.spms.common.HttpTools;
import com.migu.spms.common.JsonTool;
import com.migu.spms.common.StringUtil;
import com.migu.spms.constant.Constant;
import com.migu.spms.dao.entity.ChangeHistoryCriteria;
import com.migu.spms.dao.entity.FunctionRequireCriteria;
import com.migu.spms.dao.entity.FunctionRequireDO;
import com.migu.spms.dao.entity.ProjectCriteria;
import com.migu.spms.dao.entity.RequireUserCriteria;
import com.migu.spms.dao.entity.RequireUserDO;
import com.migu.spms.dao.entity.SubParentRequireCriteria;
import com.migu.spms.dao.inf.IBaseLineDO;
import com.migu.spms.dao.inf.IFunctionRequireDO;
import com.migu.spms.dao.inf.IRequireUserDO;
import com.migu.spms.dao.inf.ISubParentRequireDO;
import com.migu.spms.service.data.BaseLineVersion;
import com.migu.spms.service.data.FunctionRequireCompare;
import com.migu.spms.service.data.TestBaseLine;
import com.migu.spms.service.inf.IFunctionCommonService;
import com.migu.spms.service.inf.IFunctionFlowService;
import com.migu.spms.utils.PropertiesCopyUtil;
import com.migu.spms.webapi.data.BaseLineVersionRequest;
import com.migu.spms.webapi.data.EditRequireRequest;
import com.migu.spms.webapi.data.User;

@Component(value = "functionCommonServiceImpl")
public class FunctionCommonServiceImpl implements IFunctionCommonService {
	private static Logger logger = LoggerFactory.getLogger(FunctionCommonServiceImpl.class);

	@Resource(name = "IBaseLineDO")
	private IBaseLineDO baseLineDao;

	@Resource(name = "IFunctionRequireDO")
	private IFunctionRequireDO functionRequireDao;

	@Resource(name = "ISubParentRequireDO")
	private ISubParentRequireDO subParentRequireDao;

	@Resource(name = "runtimeService")
	private RuntimeService runtimeService;

	@Resource(name = "IRequireUserDO")
	private IRequireUserDO requireUserDao;

	@Resource(name = "changeHistoryServiceImpl")
	private ChangeHistoryServiceImpl changeHistoryService;
	
	@Resource(name = "IRequireUserDO")
	private IRequireUserDO requireUserDO;
	
	@Resource(name = "functionFlowServiceImpl")
	private IFunctionFlowService functionFlowService;
	
	@Value("${VersionService}")
	private String VersionServiceUrl;

	@Override
	public List<BaseLineVersion> queryBaselineVersion(BaseLineVersionRequest baseLineVersionRequest, String sessionId) {
		List<BaseLineVersion> baseLineResponse = new ArrayList<BaseLineVersion>();
		String postRequest = JSON.toJSONString(baseLineVersionRequest);
		logger.debug("发送获取基线版本请求："+VersionServiceUrl+Constant.Url.BASELINEVERSION + sessionId);
		String result = HttpTools.postRequest(VersionServiceUrl+Constant.Url.BASELINEVERSION + sessionId, "", postRequest, 500000);
		logger.debug("获取基本版本号："+result);
		if (!StringUtil.isEmpty(result)) {
			// 查询单前最大的基线版本号
			String maxBaseLineVersion = null;
			if (baseLineVersionRequest.getRequireIdList() != null && baseLineVersionRequest.getRequireIdList() != "") {
				List<String> requireIds = (List<String>) baseLineVersionRequest.getRequireIdList();
				if (requireIds.size() > 0) {
					FunctionRequireCriteria functionRequirementCriteria = new FunctionRequireCriteria();
					functionRequirementCriteria.setProjectId(baseLineVersionRequest.getProject_id());
					functionRequirementCriteria.setRequireIdList(requireIds);
					maxBaseLineVersion = functionRequireDao.queryMaxBaseLine(functionRequirementCriteria);
				}
			}
			// 获取所有基线版本号
			TestBaseLine baseLineList = (TestBaseLine) JsonTool.setJsonToObject(result,
					new TypeReference<TestBaseLine>() {
					}, false);
			// 查询已经打基线的基线版本号
			List<String> baseLined = functionRequireDao.selectAllBaseLined(baseLineVersionRequest.getProject_id());
			// 筛选符合条件的基线版本号
			if(baseLineVersionRequest.getOperator().equals(Constant.flowOperate.TRANFER_TEST)){
				if (baseLineList.getResult() != null && baseLineList.getResult().size() > 0) {
					for (BaseLineVersion baseLineVersion : baseLineList.getResult()) {
						String baseLine = baseLineVersion.getVersion_num();
						if (!StringUtil.isEmpty(baseLine)) {
							baseLineResponse.add(baseLineVersion);
//							if (!StringUtil.isEmpty(maxBaseLineVersion) && (maxBaseLineVersion.compareTo(baseLine) <= 0)) {
//								baseLineResponse.add(baseLineVersion);
//							} else if (StringUtil.isEmpty(maxBaseLineVersion)) {
//								baseLineResponse.add(baseLineVersion);
//							}
						}
					}
				}
			}else{
				if (baseLineList.getResult() != null && baseLineList.getResult().size() > 0) {
					for (BaseLineVersion baseLineVersion : baseLineList.getResult()) {
						String baseLine = baseLineVersion.getVersion_num();
						if(!baseLined.contains(baseLine)){
							baseLineResponse.add(baseLineVersion);
						}
//						if (!baseLined.contains(baseLine) && !StringUtil.isEmpty(baseLine)) {
//							if (!StringUtil.isEmpty(maxBaseLineVersion) && (maxBaseLineVersion.compareTo(baseLine) < 0)) {
//								baseLineResponse.add(baseLineVersion);
//							} else if (StringUtil.isEmpty(maxBaseLineVersion)) {
//								baseLineResponse.add(baseLineVersion);
//							}
//						}
					}
				}
			}
		}
		return baseLineResponse;

	}

	@Override
	public void deleteRequirement(Long id) {
		// 查询所有的关联需求id
		String deleteRequireIdString = subParentRequireDao.getSubParentRequireList(id.toString());
		String[] deleteRequireIds = deleteRequireIdString.split(",");
		List<String> processInstanceIds = functionRequireDao.queryProcessInstanceIdList(deleteRequireIds);
		for (String processInstanceId : processInstanceIds) {
			if (!StringUtil.isEmpty(processInstanceId)) {
				runtimeService.deleteProcessInstance(processInstanceId, "删除需求");
			}
		}
		// 批量删除需求id,还需增加删除各基线版本号
		List<String> baseLineRequireIds = functionRequireDao.selectAllIdByRequirementId(deleteRequireIds);
		if (!baseLineRequireIds.isEmpty()) {
			functionRequireDao.batchDeleteIds(baseLineRequireIds.toArray(new String[baseLineRequireIds.size()]));
		}
		// 删除父需求id
		SubParentRequireCriteria record = new SubParentRequireCriteria();
		record.setParentRequireId(id);
		subParentRequireDao.deleteByCreteria(record);
		// 删除关联子需求
		subParentRequireDao.batchDeleteRequirementIds(deleteRequireIds);
	}

	@Override
	public void updateScheduleInfo(EditRequireRequest record, com.migu.spms.service.data.User user) throws Exception {
		
		
		
		
		List<String> updateIds = new ArrayList<String>();//?
		// 更新开发人员及测试人员表
		List<String> updateRelateIds = new ArrayList<String>();//就是需求ID的字符串格式
		List<User> testers = record.getTesters();
		List<User> developers = record.getDevelopers();
		List<Long> ids = record.getIds();//需求ID
		for (Long id : ids) {//遍历需求（插入历史，更新主表信息）
			
			//清空时间，后台没法接收""，要求前端传0，现在处理回来
//			int[] changeList = record.initTime();
			
			FunctionRequireDO functionRequireDO = functionRequireDao.selectByPrimaryKey(id);
			// 插入历史
			FunctionRequireCompare functionRequireOld = PropertiesCopyUtil.parse(functionRequireDO,
					FunctionRequireCompare.class);//原需求对象（读取数据库当前状态）
			FunctionRequireCompare functionRequireOld_new = PropertiesCopyUtil.parse(functionRequireDO,
					FunctionRequireCompare.class);//同上，用于变更？
			FunctionRequireCriteria functionRequireCriteria = PropertiesCopyUtil.parse(record,
					FunctionRequireCriteria.class);//新需求（读取的record数据）
			functionRequireCriteria.setId(id);
			PropertiesCopyUtil.copyNotNull(functionRequireCriteria, functionRequireOld_new);
			FunctionRequireCompare functionRequireNew = PropertiesCopyUtil.copy(functionRequireOld_new,
					FunctionRequireCompare.class);//最终的新需求（以上代码绕圈圈赋值得到）
			
			//历史记录保存玩以后，重置时间
//			record.resetTime(changeList);
			
			
			//编辑后的人员
			if(null != developers && developers.size() > 0){
                String userNames = "";
                for (com.migu.spms.webapi.data.User us : developers) {
                    userNames += us.getUserName()+",";
                }
                functionRequireNew.setDeveloperStr(userNames.substring(0, userNames.lastIndexOf(",")));
            }
            if(null != testers && testers.size() > 0){
                String userNames = "";
                for (com.migu.spms.webapi.data.User us : testers) {
                    userNames +=us.getUserName()+",";
                }
                functionRequireNew.setTesterStr(userNames.substring(0, userNames.lastIndexOf(",")));
            }
            //更新前的记录
            //开发人员
            RequireUserCriteria requireUserCriteria = new RequireUserCriteria();
            requireUserCriteria.setFunctionRequireId(id);
            requireUserCriteria.setRoleId(Constant.Role.DEVELOPER);
            List<RequireUserDO> developers_old = requireUserDO.selectByCriteria(requireUserCriteria);
            if(null != developers && developers.size() > 0){
                String userNames = "";
                for (RequireUserDO requireUserDO : developers_old) {
                    userNames += requireUserDO.getUserName()+",";
                    functionRequireOld.setDeveloperStr(userNames.substring(0, userNames.lastIndexOf(",")));
                }
            }
            //测试人员
            requireUserCriteria.setRoleId(Constant.Role.TESTER);
            List<RequireUserDO> testers_old = requireUserDO.selectByCriteria(requireUserCriteria);
            if(null != testers && testers.size() > 0){
                String userNames = "";
                for (RequireUserDO requireUserDO : testers_old) {
                    userNames += requireUserDO.getUserName()+",";
                    functionRequireOld.setTesterStr(userNames.substring(0, userNames.lastIndexOf(",")));
                }
            }
            
			ChangeHistoryCriteria history = new ChangeHistoryCriteria();
			history.setCreateId(Long.valueOf(user.getUserId()));
			history.setCreateName(user.getUserName());
			history.setCreateTime(new Date());
			history.setIsDetails("0");
			history.setIsPermit("0");
			history.setIsBaseLine(Integer.toString(functionRequireDO.getIsBaseLine()));
			history.setFunctionRequireId(id);
			history.setBaselineVersion(functionRequireDO.getBaselineVersion());
			changeHistoryService.inesertChangeHistoryCommon(history, functionRequireOld, functionRequireNew);
			
			
			//更新主表信息
			if (!StringUtil.isEmpty(functionRequireDO.getStatus())) {
				String status = functionRequireDO.getStatus();
				if (status.equals(Constant.flowStatus.DEVELOPING)) {//开发中
					functionRequireCriteria.setDevelopResponsibleId(null);
					functionRequireCriteria.setDevelopResponsibleName(null);
					// 更新功能需求主表信息
					functionRequireDao.updateByPrimaryKeySelective(functionRequireCriteria);
				} else if (status.equals(Constant.flowStatus.NEWING)) {//新建？
					updateIds.add(id.toString());
				} else {
					// 开发人员无法更新
					functionRequireCriteria.setDevelopResponsibleId(null);
					functionRequireCriteria.setDevelopResponsibleName(null);
					functionRequireCriteria.setTestResponsibleId(null);
					functionRequireCriteria.setTestResponsibleName(null);
					// 更新功能需求主表信息
					functionRequireDao.updateByPrimaryKeySelective(functionRequireCriteria);
				}
			} else {//状态为空或者为“新建”时--插入列表
				updateIds.add(id.toString());
			}
			updateRelateIds.add(id.toString());
		}//遍历需求（插入历史，更新主表信息）完成
		
		
		// 更新主表信息
		if (updateIds.size() > 0) {
			FunctionRequireCriteria updateFunctionRequireCriteria = PropertiesCopyUtil.parse(record,
					FunctionRequireCriteria.class);
			functionRequireDao.batchUpdateRequiremntSchedule(updateIds, updateFunctionRequireCriteria);
		  for(String id:updateIds){
			  //启动流程
			  FunctionRequireDO functionRequireDO=functionRequireDao.selectByPrimaryKey(Long.valueOf(id));
		      if(functionRequireDO.getTaskId()==null&&StringUtil.isEmpty(functionRequireDO.getTaskId())){
		    	  functionFlowService.startProcessFlow(Long.valueOf(id), user);
		      }
		  }
		}
		
		// 删除开发人员及测试人员信息
		if (updateRelateIds.size() > 0) {
			
			boolean hasDev = (null != developers);//如果是空列表，清空之
			boolean hasTest = (null!=testers);
			if(hasDev){				
				requireUserDao.batchDeleteByRoleId(updateRelateIds, Constant.Role.DEVELOPER);
			}
			if(hasTest){
				requireUserDao.batchDeleteByRoleId(updateRelateIds, Constant.Role.TESTER);
			}
			
			List<RequireUserCriteria> updateRequireUser = new ArrayList<RequireUserCriteria>();
			for (String id : updateRelateIds) {
				// 增加开发人员列表
				if (null != developers && developers.size() > 0) {//!developers.isEmpty() java.lang.NullPointerException
					for (User developerUser : developers) {
						RequireUserCriteria requireUserCriteria = new RequireUserCriteria();
						requireUserCriteria.setFunctionRequireId(Long.valueOf(id));
						requireUserCriteria.setRoleId(Constant.Role.DEVELOPER);
						requireUserCriteria.setUserId(developerUser.getUserId());
						requireUserCriteria.setUserName(developerUser.getUserName());
						updateRequireUser.add(requireUserCriteria);
					}
				}
				// 增加测试人员列表
				if (null!=testers && testers.size() > 0) {//!testers.isEmpty() java.lang.NullPointerException
					for (User testUser : testers) {
						RequireUserCriteria requireUserCriteria = new RequireUserCriteria();
						requireUserCriteria.setFunctionRequireId(Long.valueOf(id));
						requireUserCriteria.setRoleId(Constant.Role.TESTER);
						requireUserCriteria.setUserId(testUser.getUserId());
						requireUserCriteria.setUserName(testUser.getUserName());
						updateRequireUser.add(requireUserCriteria);
					}
				}
			}
			if (updateRequireUser.size() > 0) {
				requireUserDao.batchInsert(updateRequireUser);
			}
		}
	}

	public List<BaseLineVersion> queryAllBaseVersion(ProjectCriteria record) {
		List<String> allBaseLineVersion = functionRequireDao.queryAllBaseLineVersion(record.getKeyword(),record.getProjectId());
		List<BaseLineVersion> baseVersionResponse = new ArrayList<BaseLineVersion>();
		for (String baseLineVersion : allBaseLineVersion) {
			BaseLineVersion baseLineVersion1 = new BaseLineVersion();
			baseLineVersion1.setVersion_num(baseLineVersion);
			baseVersionResponse.add(baseLineVersion1);
		}
		return baseVersionResponse;
	}

	/*	*//**
			 * 模糊查询添加条件
			 *//*
			 * private void addPageQuery(BaseLineVersionRequest
			 * baseLineVersionRequest) throws Exception { int pageNo =
			 * baseLineVersionRequest.getPageNo(); int pageSize =
			 * baseLineVersionRequest.getPageSize(); int rowStar = (pageNo - 1)
			 * * pageSize; int rowEnd = pageNo * pageSize - 1;
			 * functionRequireCriteria.setRowSrt(rowStar);
			 * functionRequireCriteria.setRowEnd(rowEnd); }
			 */

}
